//
//  ChartDataVC.m
//  PearRich
//
//  Created by Jinniu on 2020/3/21.
//  Copyright © 2020 谢黎鹏. All rights reserved.
//

#import "ChartDataVC.h"
#import "PRMainViewModel.h"
#import "ZHLineChartView.h"
#import <PGDatePicker/PGDatePickManager.h>
@interface ChartDataVC ()<PGDatePickerDelegate>
{
    NSMutableArray * _xArr, *_ySaleArr , * _yProfitArr;
    UIScrollView * _bgScro;
    ZHLineChartView * _lineView ,* _profitView;
    UIButton * _dateBtn;
    NSInteger _xNumber;
    NSDate * _choseDate;
    BOOL _isMonth;
    CGFloat _totalSale, _totalProfit;
    UILabel * _totalSaleLab ,* _totalProfitLab;
}
@end

@implementation ChartDataVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTitle = @"图表";
    self.view.backgroundColor = [UIColor normalColor:UIColorWhite darkColor:UIColorBlack];
    _xArr = [NSMutableArray new];
    _choseDate = [NSDate date];
    _ySaleArr = [NSMutableArray new];
    _yProfitArr = [NSMutableArray new];
    //初始化默认按月
    _isMonth = YES;
    XHQHUDInTextView(self.view, @"加载中");
    [self setupXnumberArray];
    
    [self createUI];
    XHQHUDHide();
}
-(void)setupXnumberArray{
    if (_isMonth) {
        _xNumber = [Mytools howManyDaysInThisYear:_choseDate.year withMonth:_choseDate.month];
    }else{
        _xNumber = 12;
    }
    for (int i =0; i<_xNumber; i++) {
        NSString * str = @"";
        if (_isMonth) {
            str = [NSString stringWithFormat:@"%d",i+1];
        }else{
            str = [NSString stringWithFormat:@"%d月",i+1];
        }
        [_xArr addObject:str];
    }
    [self getData];
}
-(void)getData{
    NSMutableArray * tmpArr = [NSMutableArray new];
    NSMutableArray * profitArr = [NSMutableArray new];
    for (int i =0; i<_xNumber; i++) {
        NSArray * arr = nil;
        if (_isMonth) {
            arr =  [PRMainViewModel bg_find:GoodsInfoTab type:bg_createTime dateTime:[NSString stringWithFormat:@"%ld-%02ld-%02d",_choseDate.year,_choseDate.month,i+1]];
        }else{
            arr =  [PRMainViewModel bg_find:GoodsInfoTab type:bg_createTime dateTime:[NSString stringWithFormat:@"%ld-%02d",_choseDate.year,i+1]];
        }
        if (arr.count>0) {
            CGFloat val = 0;
            CGFloat profit = 0;
            for (PRMainViewModel * mo in arr) {
                for (GoodsInfoModel * mp  in mo.goodsInfoArr) {
                    if ([mp.goodsCount intValue]>0) {//最后一个是空模型
                        CGFloat tmpp = [mp.goodsCount intValue] * [mp.sellPrice floatValue];
                        _totalSale += tmpp;
                        val += tmpp;
                        profit += [mp.goodsCount intValue] * ([mp.sellPrice floatValue] - [mp.buyPrice floatValue]);
                    }
                }
                profit -= [mo.mailFee floatValue];
            }
            [tmpArr addObject:@(val)];
            [profitArr addObject:@(profit)];
        }else{
            [tmpArr addObject:@(0)];
            [profitArr addObject:@(0)];
        }
    }
    [_ySaleArr addObjectsFromArray:tmpArr];
    [_yProfitArr addObjectsFromArray:profitArr];
    
    NSArray * pieArr = nil;
    if (_isMonth) {
        pieArr = [PRMainViewModel bg_find:GoodsInfoTab type:bg_createTime dateTime:[NSString stringWithFormat:@"%ld-%02ld",_choseDate.year,_choseDate.month]];
    }else{
        pieArr = [PRMainViewModel bg_find:GoodsInfoTab type:bg_createTime dateTime:[NSString stringWithFormat:@"%ld",_choseDate.year]];
    }
    NSMutableDictionary * dic = [NSMutableDictionary new];
    for (PRMainViewModel * mo in pieArr) {
        for (GoodsInfoModel * mp  in mo.goodsInfoArr) {
            if (mp.goodsName.length>0) {
                CGFloat profit = [mp.goodsCount floatValue] * ([mp.sellPrice floatValue] - [mp.buyPrice floatValue]);
                _totalProfit += profit;
                if ([[dic allKeys] containsObject:mp.goodsName]) {
                    CGFloat pr = [dic[mp.goodsName] floatValue] + profit;
                    [dic setObject:@(pr) forKey:mp.goodsName];
                }else{
                    [dic setObject:@(profit) forKey:mp.goodsName];
                }
            }
        }
        _totalProfit -= [mo.mailFee floatValue];
    }
}
-(void)createUI{
    UISegmentedControl *seg = [[UISegmentedControl alloc]initWithItems:@[@"按月",@"按年"]];
    seg.frame = Frame(10, kTopHeight + 10, 100, 30);
    seg.selectedSegmentIndex = 0;
    [seg setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor darkGrayColor]}forState:UIControlStateNormal];
    [seg setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}forState:UIControlStateSelected];
    [seg addTarget:self action:@selector(didClicksegmentedControlAction:)forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:seg];
    
    NSDate * date = [NSDate date];
    _dateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _dateBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_dateBtn setTitleColor:[UIColor normalColor:[UIColor darkGrayColor] darkColor:UIColorWhite] forState:UIControlStateNormal];
    [_dateBtn setTitle:[NSString stringWithFormat:@"%ld-%02ld",date.year,date.month] forState:UIControlStateNormal];
    _dateBtn.layer.borderColor = [UIColor darkGrayColor].CGColor;
    _dateBtn.layer.borderWidth = 0.7;
    _dateBtn.cornerRadius =4;
    [_dateBtn addTarget:self action:@selector(choseDateBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_dateBtn];
    _dateBtn.sd_layout.rightSpaceToView(self.view, 10).centerYEqualToView(seg);
    [_dateBtn setupAutoSizeWithHorizontalPadding:10 buttonHeight:30];
    
    _bgScro = [UIScrollView new];
    [self.view addSubview:_bgScro];
    _bgScro.sd_layout.leftEqualToView(self.view).rightEqualToView(self.view).topSpaceToView(_dateBtn, 0).bottomSpaceToView(self.view, KTabbarSafeBottomMargin);
    
    _totalSaleLab = [UILabel labelWithTitle:[NSString stringWithFormat:@"总销售额：%.2lf",_totalSale] color:[UIColor normalColor:UIColorBlack darkColor:UIColorWhite] fontSize:14];
    [_bgScro addSubview:_totalSaleLab];
    _totalSaleLab.sd_layout.leftSpaceToView(_bgScro, 15).topSpaceToView(_bgScro, 15).heightIs(16);
    [_totalSaleLab setSingleLineAutoResizeWithMaxWidth:300];
    
    _totalProfitLab = [UILabel labelWithTitle:[NSString stringWithFormat:@"总利润：%.2lf",_totalProfit] color:[UIColor normalColor:UIColorBlack darkColor:UIColorWhite] fontSize:14];
    [_bgScro addSubview:_totalProfitLab];
    _totalProfitLab.sd_layout.rightSpaceToView(_bgScro, 15).centerYEqualToView(_totalSaleLab).heightIs(16);
    [_totalProfitLab setSingleLineAutoResizeWithMaxWidth:300];
    
    NSString * lab1Str = @"销售额";
    UILabel * lab1 = [UILabel labelWithTitle:lab1Str color:[UIColor normalColor:UIColorBlack darkColor:UIColorWhite] fontSize:14];
    lab1.frame = Frame(15, 10, [lab1Str sizeWithFont:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(300, 20)].width, 14);
    [_bgScro addSubview:lab1];
    lab1.sd_layout.leftSpaceToView(_bgScro, 15).topSpaceToView(_totalSaleLab, 10).heightIs(14);
    [lab1 setSingleLineAutoResizeWithMaxWidth:300];
    
    [self setupSaleChartView];
    
    NSString * lab2Str = @"利润";
    UILabel * lab2 = [UILabel labelWithTitle:lab2Str color:[UIColor normalColor:UIColorBlack darkColor:UIColorWhite] fontSize:14];
    lab2.frame = Frame(15, CGRectGetMaxY(_lineView.frame)+10, [lab2Str sizeWithFont:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(300, 20)].width, 14);
    [_bgScro addSubview:lab2];
    [self setupProfitChartView];
    [_bgScro setupAutoContentSizeWithBottomView:_profitView bottomMargin:10];
}
-(void)setupProfitChartView{
    int maxValueAtArray = [[_yProfitArr valueForKeyPath:@"@max.intValue"] intValue];
    int minValueAtArray = [[_yProfitArr valueForKeyPath:@"@min.intValue"] intValue];
    
    _profitView = [[ZHLineChartView alloc] initWithFrame:Frame(0, CGRectGetMaxY(_lineView.frame)+10+14+10, IPHONE_WIDTH, 200)];
    _profitView.max = @(maxValueAtArray);
    _profitView.min = @(minValueAtArray);
    _profitView.horizontalDataArr = _xArr.copy;
    _profitView.lineDataAry = _yProfitArr.copy;
    _profitView.splitCount = 4;
    _profitView.toCenter = NO;
    _profitView.isShowHeadTail = _xArr.count>12?YES:NO;
    _profitView.angle = 0;
    _profitView.backgroundColor = [UIColor normalColor:UIColorWhite darkColor:UIColorBlack];
    [_bgScro addSubview:_profitView];
    [_profitView drawLineChart];
}
-(void)setupSaleChartView{
    int maxValueAtArray = [[_ySaleArr valueForKeyPath:@"@max.intValue"] intValue];
    int minValueAtArray = [[_ySaleArr valueForKeyPath:@"@min.intValue"] intValue];
    
    _lineView = [[ZHLineChartView alloc] initWithFrame:Frame(0, 10+14+10, IPHONE_WIDTH, 200)];
    _lineView.max = @(maxValueAtArray);
    _lineView.min = @(minValueAtArray);
    _lineView.horizontalDataArr = _xArr.copy;
    _lineView.lineDataAry = _ySaleArr.copy;
    _lineView.splitCount = 4;
    _lineView.toCenter = NO;
    _lineView.isShowHeadTail = _xArr.count>12?YES:NO;
    _lineView.angle = 0;
    _lineView.backgroundColor = [UIColor normalColor:UIColorWhite darkColor:UIColorBlack];
    [_bgScro addSubview:_lineView];
    [_lineView drawLineChart];
}
-(void)removeChartView{
    [_lineView removeFromSuperview];
    _lineView = nil;
    [_profitView removeFromSuperview];
    _profitView = nil;
}
-(void)didClicksegmentedControlAction:(UISegmentedControl*)seg{
    NSInteger Index = seg.selectedSegmentIndex;
    [self removeArray];
    if (Index==0) {
        _isMonth = YES;
        [self setupXnumberArray];
        [_dateBtn setTitle:[NSString stringWithFormat:@"%ld-%02ld",_choseDate.year,_choseDate.month] forState:UIControlStateNormal];
    }else{
        _isMonth = NO;
        [self setupXnumberArray];
        [_dateBtn setTitle:[NSString stringWithFormat:@"%ld",_choseDate.year] forState:UIControlStateNormal];
    }
    [self removeChartView];
    [self setupViews];
}
-(void)removeArray{
    [_xArr removeAllObjects];
    [_ySaleArr removeAllObjects];
    [_yProfitArr removeAllObjects];
    _totalSale = 0;
    _totalProfit = 0;
}
-(void)setupViews{
    [self setupSaleChartView];
    [self setupProfitChartView];
    _totalSaleLab.text = [NSString stringWithFormat:@"总销售额：%.2lf",_totalSale];
    _totalProfitLab.text = [NSString stringWithFormat:@"总利润：%.2lf",_totalProfit];
}
-(void)choseDateBtnClick{
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    datePickManager.headerViewBackgroundColor = [UIColor whiteColor];
    datePickManager.isShadeBackground = true;
    datePickManager.confirmButtonTextColor = ThemeColor;
    
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.isHiddenMiddleText = false;
    datePicker.delegate = self;
    datePicker.textColorOfSelectedRow = [UIColor blackColor];
    datePicker.textColorOfOtherRow = [UIColor colorWithHue:0 saturation:0 brightness:0.36 alpha:1];
    datePicker.lineBackgroundColor = [UIColor colorWithHue:0 saturation:0 brightness:0.36 alpha:1];
    datePicker.datePickerMode = _isMonth?PGDatePickerModeYearAndMonth:PGDatePickerModeYear;
    datePicker.maximumDate = [NSDate date];
    [self presentViewController:datePickManager animated:NO completion:nil];
}
#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents  {
    /*dateComponents格式：Calendar Year: 2018  Month: 1  Leap month: no  Day: 26  Hour: 8  Minute: 49  Second: 32  Weekday: 3*/
    NSString * datestr = @"";
    if (_isMonth) {
        [_dateBtn setTitle:[NSString stringWithFormat:@"%ld-%02ld",dateComponents.year,dateComponents.month] forState:UIControlStateNormal];
        datestr = [NSString stringWithFormat:@"%ld-%02ld-01 00:00:00",dateComponents.year,dateComponents.month];
    }else{
        [_dateBtn setTitle:[NSString stringWithFormat:@"%ld",dateComponents.year] forState:UIControlStateNormal];
        datestr = [NSString stringWithFormat:@"%ld-01-01 00:00:00",dateComponents.year];
    }
    _choseDate = [Mytools dateStrToDate:datestr];
    [self removeArray];
    [self setupXnumberArray];
    [self removeChartView];
    [self setupViews];
    
}
@end
